<template>
  <div>
    <!-- 面包屑路径导航 -->
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item :to= "{path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class='box-card'>
      <!-- 搜索和添加组件区域
            @clear='getUsersList'
            @input='getUsersList'
            -->
      <el-row :gutter='20'>
        <el-col :span='7'>
          <el-input
            placeholder='请输入内容'
            v-model='searchName'
            class='input-with-select'
            clearable
          >
            <el-button
              slot='append'
              icon='el-icon-search'
              @click='searchUsers'
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span='4'>
          <el-button type='primary' @click='showadd'
            >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data='usersList' style='width: 100%' stripe border>
        <el-table-column type='index' label='#' width='50'> </el-table-column>
        <el-table-column prop='usrName' label='用户名'> </el-table-column>
        <el-table-column prop='usrPhone' label='电话'> </el-table-column>
        <el-table-column prop='roleName' label='角色名'> </el-table-column>
        <el-table-column prop='grpName' label='组名'> </el-table-column>
        <el-table-column prop='usrFlag' label='用户状态'>
          <template slot-scope='scope'>
            <el-button  size="mini" v-if="scope.row.usrFlag === 1" type="success" icon="el-icon-check" circle></el-button>
            <el-button  size="mini" v-else type="danger" icon="el-icon-close" circle></el-button>
          </template>
        </el-table-column>
        <el-table-column label='操作' min-width="">
          <template v-if="scope.row.usrName != 'admin'" slot-scope='scope'>
            <el-button
             size="mini"
              type='primary'
              icon='el-icon-edit'
              circle
              @click='showEditDialog(scope.row.usrId)'
            ></el-button>
            <el-tooltip
              class='item'
              effect='dark'
              content='分配角色'
              placement='top'
            >
              <el-button
               size="mini"
                type='warning'
                icon='el-icon-star-off'
                circle
                @click='showDispatcherRoleDialog(scope.row.usrId, scope.row.usrRoleId)'
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class='item'
              effect='dark'
              content='分配组'
              placement='top'
            >
             <el-button
              size="mini"
              type="info"
              icon="el-icon-message"
              @click='showDispatcherGroupDialog(scope.row.usrId, scope.row.usrGrpId)'
              circle>
            </el-button>
            </el-tooltip>
            <el-button
             size="mini"
              type='danger'
              icon='el-icon-delete'
              circle
              @click='del(scope.row.usrId)'
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change='handleSizeChange'
        @current-change='handleCurrentChange'
        :current-page='page'
        :page-sizes='[5, 10, 15, 20]'
        :page-size='rows'
        layout='total, sizes, prev, pager, next, jumper'
        :total='total'
      >
      </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      title='添加'
      :visible.sync='addDialogVisible'
      width='50%'
      @close='clearAddForm'
    >
      <!-- 对话框主体内容 -->
      <el-form
        ref='addForm'
        :rules='addFormRules'
        :model='addForm'
        label-width='80px'
      >
        <el-form-item label='用户名' prop='usrName'>
          <el-input v-model='addForm.usrName'></el-input>
        </el-form-item>
        <el-form-item label='电话' prop='usrPhone'>
          <el-input v-model='addForm.usrPhone'></el-input>
        </el-form-item>
        <el-form-item label='密码' prop='usrPassword'>
          <el-input type='password' v-model='addForm.usrPassword'></el-input>
        </el-form-item>
        <el-form-item label='用户角色'  prop='usrRoleId'>
          <el-select v-model='addForm.usrRoleId' placeholder='请选择用户角色'>
              <el-option v-for="item in roleList" v-bind:key="item.roleId" :label='item.roleName' :value='item.roleId'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='用户组'  prop='usrGrpId'>
          <el-select v-model='addForm.usrGrpId' placeholder='请选择用户组'>
              <el-option v-for="item in groupList" v-bind:key="item.grpId" :label='item.grpName' :value='item.grpId'></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框的操作按钮 -->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='addDialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='add'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      title='修改'
      :visible.sync='editDialogVisible'
      width='50%'
      @close='clearEditForm'
    >
      <!-- 对话框主体内容 -->
      <el-form
        ref='editForm'
        :rules='editFormRules'
        :model='editForm'
        label-width='80px'
      >
        <el-form-item label='用户名' prop='usrName'>
          <el-input v-model='editForm.usrName' disabled></el-input>
        </el-form-item>
        <el-form-item label='电话' prop='usrPhone'>
          <el-input v-model='editForm.usrPhone'></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <template>
          <el-switch
            v-model="editForm.usrFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value='1'
            :inactive-value='2'>
          </el-switch>
          </template>
        </el-form-item>
      </el-form>
      <!-- 对话框的操作按钮 -->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='editDialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='edit'>确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title='分配角色' :visible.sync='dispatcherDialogVisibleRole' width='50%'>
      <!-- 对话框主体内容 -->
      <el-form :model='dispatcherRole' label-width='80px'>
        <!-- 角色列表 -->
        <el-form-item label='选择要修改的角色' label-width="200px">
          <el-select v-model='dispatcherRole.usrRoleId' placeholder='请选择'>
            <el-option
              v-for='role in roleList'
              :key='role.roleId'
              :label='role.roleName'
              :value='role.roleId'
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框的操作按钮 -->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='dispatcherDialogVisibleRole = false'>取 消</el-button>
        <el-button type='primary' @click='dispacher(0)'>确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配组对话框 -->
    <el-dialog title='分配组' :visible.sync='dispatcherDialogVisibleGroup' width='50%'>
      <!-- 对话框主体内容 -->
      <el-form :model='dispatcherGroup' label-width='80px'>
        <!-- 角色列表 -->
        <el-form-item label='选择要修改的组' label-width="200px">
          <el-select v-model='dispatcherGroup.usrGrpId' placeholder='请选择'>
            <el-option
              v-for='group in groupList'
              :key='group.grpId'
              :label='group.grpName'
              :value='group.grpId'
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框的操作按钮 -->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='dispatcherDialogVisibleGroup = false'>取 消</el-button>
        <el-button type='primary' @click='dispacher(1)'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 搜索的关键字
      searchName: '',
      // 用户列表集合
      usersList: [],
      // 页码
      page: 1,
      // 单页显示条数
      rows: 5,
      // 总数据条数
      total: 0,
      // 是否显示添加对话框
      addDialogVisible: false,
      // 是否显示修改对话框
      editDialogVisible: false,
      // 是否显示分配对话框
      dispatcherDialogVisibleRole: false,
      // 是否显示分配组对话框
      dispatcherDialogVisibleGroup: false,
      // 添加表单对象
      addForm: {
        usrName: '',
        usrPhone: '',
        usrPassword: '',
        usrRoleId: '',
        usrGroupId: ''
      },
      addFormRules: {
        usrName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 4, max: 15, message: '长度在4-15之间', trigger: 'blur' }
        ],
        usrPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 10, message: '6-10位密码', trigger: 'blur' }
        ],
        usrPhone: [
          { min: 11, max: 11, required: true, message: '电话格式不合法', trigger: 'blur' }
        ],
        usrRoleId: [
          { required: true, message: '请选择用户对应的角色', trigger: 'blur' }
        ],
        usrGroupId: [
          { required: true, message: '请选择用户所在组', trigger: 'blur' }
        ]
      },
      // 修改表单对象
      editForm: {
        usrName: '',
        usrPhone: '',
        usrFlag: 1
        // usrPassword: '',
        // usrRoleId: '',
        // usrGroupId: ''
      },
      editFormRules: {
        usrPhone: [
          { min: 11, max: 11, required: true, message: '电话格式不合法', trigger: 'blur' }
        ]
      },
      // 分配角色表单
      dispatcherRole: {
        usrId: '',
        usrRoleId: ''
      },
      // 分配角色表单
      dispatcherGroup: {
        usrId: '',
        usrGrpId: ''
      },
      // 角色集合
      roleList: [],
      // 组集合
      groupList: []
    }
  },
  methods: {
    async getUsersList () {
      const param = {
        page: this.page,
        rows: this.rows,
        uName: this.searchName
      }
      const { data: result, status: state } = await this.$http.post(
        'user-server/user/getUsers',
        this.$qs.stringify(param)
      )
      if (state !== 200) {
        return this.$message.error('查询失败')
      }
      this.usersList = result.records
      this.total = result.total
    },
    handleSizeChange (size) {
      this.rows = size
      this.getUsersList()
    },
    handleCurrentChange (page) {
      // 将需要访问的页面赋值给vue的遍历page
      this.page = page
      // 然后重写调用查询方法，查询方法会使用最新的page进行分页查询
      this.getUsersList()
    },
    searchUsers () {
      this.getUsersList()
    },
    clearAddForm () {
      // 初始化添加表单数据
      this.$refs.addForm.resetFields()
    },
    showadd () {
      // 查询所有用户组
      this.getGroupAll()
      // 查询所有角色
      this.getRoleAll()

      // 显示添加对话框
      this.addDialogVisible = true
    },
    clearEditForm () {
      // 初始化修改表单数据
      this.$refs.editForm.resetFields()
    },
    add () {
      // 触发验证
      this.$refs.addForm.validate(async valid => {
        if (!valid) {
          return
        }
        // 验证用户名是否已经存在，不存在就添加
        const response = await this.$http.post('user-server/user/isExits', this.addForm)
        if (response.data.result !== 'SUCCESS') {
          this.$message.error(response.data.message)
        } else {
          this.$message.success('添加成功！')
        }
        // 3、关闭对话框
        this.addDialogVisible = false
        // 4、刷新表格数据
        this.getUsersList()
      })
    },
    del (id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$http.post('user-server/user/updateUser', { usrId: id, usrFlag: 0 }).then((result) => {
          if (result.data.result === 'SUCCESS') {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            // 刷新表格
            this.getUsersList()
          } else {
            this.$message({
              type: 'error',
              message: result.data.message
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      })
    },
    async showEditDialog (id) {
      // 1.根据id查询
      const { data: result } = await this.$http.post('user-server/user/id/' + id)
      console.log(result)
      // 2.填充到修改表单中
      this.editForm.usrId = result.data.usrId
      this.editForm.usrName = result.data.usrName
      this.editForm.usrPhone = result.data.usrPhone
      this.editForm.usrFlag = result.data.usrFlag
      // 3.显示修改对话框
      this.editDialogVisible = true
    },
    edit () {
      // 触发验证
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          return
        }
        // 1、修改数据到数据库
        this.$http.post('user-server/user/updateUser', this.editForm).then((result) => {
        // 2、根据返回结果进行弹出提示
          if (result.data.result === 'SUCCESS') {
            this.$message.success('修改成功！')
            // 3、关闭对话框
            this.editDialogVisible = false
            // 4、刷新表格数据
            this.getUsersList()
          } else {
            this.$message.error(result.data.message)
          }
        })
      })
    },
    async showDispatcherRoleDialog (id, roleId) {
      console.log(roleId)
      this.dispatcherRole.usrRoleId = roleId
      this.dispatcherRole.usrId = id

      this.getRoleAll()
      // 3.显示分配角色对话框
      this.dispatcherDialogVisibleRole = true
    },
    async showDispatcherGroupDialog (id, groupId) {
      this.dispatcherGroup.usrGrpId = groupId
      this.dispatcherGroup.usrId = id

      this.getGroupAll()
      // 3.显示分配角色对话框
      this.dispatcherDialogVisibleGroup = true
    },
    // 查询所有系统提供的角色
    async getRoleAll () {
      this.$http.get(
        'user-server/sys-role/getRoles'
      ).then((result) => {
        this.roleList = result.data.data
      })
    },
    // 查询所有系统提供的组
    async getGroupAll () {
      this.$http.get(
        'user-server/sys-group/getGroups'
      ).then((result) => {
        this.groupList = result.data.data
      })
    },
    // 分配 参数 0 分配角色 1分配组
    async dispacher (status) {
      let upObj = null
      if (status === 0) {
        upObj = this.dispatcherRole
      } else {
        upObj = this.dispatcherGroup
      }
      // 1、修改数据到数据库
      this.$http.post('user-server/user/updateUser', upObj).then((result) => {
      // 2、根据返回结果进行弹出提示
        if (result.data.result === 'SUCCESS') {
          this.$message.success('修改成功！')
          // 3、关闭对话框
          this.dispatcherDialogVisibleRole = false
          this.dispatcherDialogVisibleGroup = false
          // 4、刷新表格数据
          this.getUsersList()
        } else {
          this.$message.error(result.data.message)
        }
      })
    }
  },
  created () {
    this.getUsersList()
  }
}
</script>

<style lang='less' scoped>
.photo {
  width: 50px;
  height: 50px;
  border-radius: 5px
}
</style>
